import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {InfoCircleOutlined} from "@ant-design/icons";
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio,Tooltip,Table, message } from 'antd';
import { formatMessage, FormattedMessage} from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { getAreaByContinent } from '.././service';
import styles from '../style.less'

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  dataList: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues,dataList } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  const [continent,setContinent] = useState<any>('');
  const [nation,setNation] = useState<any>('');
  const [areaOptions, setAreaOptions] = useState<any>([]);

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      //查重
      if(cancelRepet(continent,nation)) return; 
      
      console.log("submit fields ", fieldsValue)
      var areaName = '';
      var langName = '';
      var writingDirection = '';
      if(common.languageOption && common.languageOption.length>0){
        common.languageOption.map((item:any,index:any)=>{
          if(item.code == fieldsValue.langCode){
            langName = item.localName;
            writingDirection = item.writingDirection;
          }
        })
      }
      if(common.areasOption && common.areasOption.length>0){
        common.areasOption.map((item:any,index:any)=>{
          if(item.code == nation){
            areaName = item.localName;
          }
        })
      }
      console.log(fieldsValue.areaStatus);
      var submitValue:any = {
        'rankNum': fieldsValue.rankNum,
        'langCode': fieldsValue.langCode,
        'langName': langName,
        'writingDirection': writingDirection,
        'language_status': fieldsValue.language_status,
        'continentId': continent,
        'areaName': fieldsValue.areaStatus == true ? (areaName || dataFormValues?.areaName) : null,
        'areaCode': fieldsValue.areaStatus == true ? (nation || dataFormValues?.areaCode) : null,
        'dateFormat': fieldsValue.dateFormat,
        'timeFormatMinute': fieldsValue.timeFormatMinute,
        'timeFormatHour': fieldsValue.timeFormatHour,
        'timeFormatDay': fieldsValue.timeFormatDay,
        'timeFormatMonth': fieldsValue.timeFormatMonth,
        'lengthUnits': fieldsValue.lengthUnits,
        'isEnable': fieldsValue.isEnable,
        'areaStatus': fieldsValue.areaStatus,
      }
      if(isUpdate){
        console.log('编辑')
        submitValue.langTag = dataFormValues.langTag;
      }

      // 如果更新成功之后，重置表单
      handleSubmit(submitValue);
      setContinent('');
      setNation('');
    });
  };

  //地区去重校验
  const cancelRepet = (con:any,nation:any)=>{
    var isRepet = false;
    if(dataList.length > 0){
      dataList.map((item:any,index:any)=>{
        if(con == item.continent && nation == item.nation){
          isRepet = true;
        }
      })

    }
    return isRepet
  }

  //通过洲ID查洲下面的地区
  const getAreaCode = (id:any) => {
    getAreaByContinent(id).then(res=>{
      if(res.code == 0){
        setAreaOptions(res.data.list)
      }else{
        message.error(res.msg);
      }
    })
  }

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={'语言设置'}
    width={"40%"}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'ranknum' })}>
      {form.getFieldDecorator('rankNum', {
        initialValue: isUpdate ? dataFormValues.rankNum : 888,
        // rules: [],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'lang_code' })}>
      {form.getFieldDecorator('langCode', {
        initialValue: isUpdate ? dataFormValues?.langCode && (dataFormValues?.langCode).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select disabled={isUpdate} placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.languageOption && TsxHelper.buildNameSelectOption(common.languageOption)}
      </Select>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="lang_area" />
        <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="如果语言不需要区分地区，则不用启用地区代码" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em>
      </span>
    }>
      {form.getFieldDecorator('areaStatus', {
        initialValue: isUpdate ? dataFormValues?.areaStatus : false,
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={false}>不启用</Radio>
          <Radio value={true}>启用</Radio>
        </Radio.Group>
      )}
    </FormItem>

    {
      form.getFieldValue('areaStatus') == true && <>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'area_code' })}>
          {form.getFieldDecorator('type', {
            // initialValue: isUpdate ? (dataFormValues.type).toString() : undefined,
            //  rules: [{ required: true, message: '请选择！',}],
          })(<Input.Group compact>
            <Select style={{width:"40%"}}
            // disabled={isUpdate && dataFormValues.continentId}
            defaultValue={(dataFormValues?.continentId)} 
            onChange={(e:any)=>{console.log(e);setContinent(e);getAreaCode(e)}}>
              {common.continentOption  && TsxHelper.buildSelectOption(common.continentOption)}
            </Select>

            <Select style={{width:"60%"}}
            //  disabled={isUpdate && dataFormValues.areaCode} 
             showSearch defaultValue={dataFormValues?.areaCode} onChange={(e:any)=>{console.log(e);setNation(e)}}>
              {areaOptions && TsxHelper.buildNameSelectOption(areaOptions)}
            </Select>
          </Input.Group>)}
        </FormItem>
      </>
    }

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="date_format" />
        <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="使用 yyyy 表示年，mm 表示月，dd 表示天。" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em>
      </span>
    }>
      {form.getFieldDecorator('dateFormat', {
        initialValue: isUpdate ? dataFormValues?.dateFormat && (dataFormValues?.dateFormat).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.dateOption && TsxHelper.buildSelectOption(common.dateOption)}
      </Select>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="length-unit" />
      </span>
    }>
      {form.getFieldDecorator('lengthUnits', {
        initialValue: isUpdate ? dataFormValues?.lengthUnits && (dataFormValues?.lengthUnits).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select placeholder={'请选择长度单位'} size={'default'} style={{ width: '100%' }}>
        {common.lengthUnitsOption && TsxHelper.buildSelectOption(common.lengthUnitsOption)}
      </Select>)}
    </FormItem>

    <FormItem
    label={
      <span >
        <FormattedMessage id="Human-time" />
        {/* <em className={styles.optional} style={{position: 'relative',bottom: 5}}>
          <Tooltip title={<FormattedMessage id="人性化时间格式变量名 {n}" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em> */}
      </span>
    }
    style={{marginBottom:5}} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      {form.getFieldDecorator('timeFormatMinute', {
        initialValue: isUpdate ? dataFormValues?.timeFormatMinute : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input addonBefore={(<span style={{display: 'inline-block', width: '91px'}}>{"{n} minute ago"}</span>)} placeholder={''} style={{position:'relative',top: 4}}/>)}
    </FormItem>
    <FormItem  label={''} style={{marginLeft: '21%',marginBottom:0,width:'62.5%'}}>
      {form.getFieldDecorator('timeFormatHour', {
        initialValue: isUpdate ? dataFormValues?.timeFormatHour : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input addonBefore={(<span style={{display: 'inline-block', width: '91px'}}>{"{n} hour ago"}</span>)} placeholder={""}/>)}
    </FormItem>
    <FormItem style={{marginLeft: '21%',marginBottom:0,width:'62.5%'}} label={''}>
      {form.getFieldDecorator('timeFormatDay', {
        initialValue: isUpdate ? dataFormValues?.timeFormatDay : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input addonBefore={(<span style={{display: 'inline-block', width: '91px'}}>{'{n}  day ago'}</span>)} placeholder={""}/>)}
    </FormItem>
    <FormItem style={{marginLeft: '21%',width:'62.5%',marginBottom:0}} label={''} extra="人性化时间格式变量名 {n}">
      {form.getFieldDecorator('timeFormatMonth', {
        initialValue: isUpdate ? dataFormValues?.timeFormatMonth : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input addonBefore={(<span style={{display: 'inline-block', width: '91px'}}>{"{n} month ago"}</span>)} placeholder={""}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="start-status" />
        {/* <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="如果语言不需要区分地区，则不用启用地区代码" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em> */}
      </span>
    }>
      {form.getFieldDecorator('isEnable', {
        initialValue: isUpdate ? dataFormValues?.isEnable : false,
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={false}>不启用</Radio>
          <Radio value={true}>启用</Radio>
        </Radio.Group>
      )}
    </FormItem>
    
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
